package com.biodiv.server.registry;

import com.biodiv.common.instance.ServiceInstance;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: tianquan
 * @date: 2024-11-03  10:39
 * @Description: 注册的服务实例
 */
@Slf4j
public class ServerInstanceManager {

    // 存储服务实例
    public static final Map<String, Set<ServiceInstance>> instances = new ConcurrentHashMap<>();

    // 删除实例
    public static void removeInstance(String serviceName, String id) {
        Set<ServiceInstance> serviceInstances = instances.get(serviceName);
        if (serviceInstances != null) {
            serviceInstances.removeIf(instance -> instance.getId().equals(id));
        }
    }

    // 删除实例
    public static void removeInstanceByHost(String host, int port) {
        for (Set<ServiceInstance> value : instances.values()) {
            for (ServiceInstance serviceInstance : value) {
                if (serviceInstance.getHost().equals(host) && serviceInstance.getSourcePort() == port) {
                    log.info("删除服务实例: {}", serviceInstance);
                    value.remove(serviceInstance);
                }
            }
        }
        // instances.forEach(((k, v) -> v.removeIf(instance -> instance.getHost().equals(host) && instance.getSourcePort() == port)));
    }

    // 更具地址和端口获取实例
    public static ServiceInstance getInstanceByHost(String host, int port) {
        for (Set<ServiceInstance> value : instances.values()) {
            for (ServiceInstance serviceInstance : value) {
                if (serviceInstance.getHost().equals(host) && serviceInstance.getPort() == port) {
                    return serviceInstance;
                }
            }
        }
        return null;
    }

    // 注册实例
    public static void registerInstance(String serviceName, ServiceInstance instance) {
        instances.forEach(((k, v) -> log.info("服务名: {}, 实例数量: {}", k, v.size())));
        Set<ServiceInstance> serviceInstances = instances.get(serviceName);
        if (serviceInstances == null) {
            serviceInstances = new HashSet<>();
            serviceInstances.add(instance);
            instances.put(serviceName, serviceInstances);
        }
        serviceInstances.add(instance);
    }

    // 根据名称获取实例
    public static Set<ServiceInstance> getInstance(String serviceName) {
        return instances.get(serviceName);
    }

    // 获取所有实例
    public static Map<String, Set<ServiceInstance>> getInstances() {
        return instances;
    }

}
